package com.gitee.sunstar.adblib

import android.os.Handler
import android.os.Looper
import android.util.Log
import java.io.BufferedReader
import java.io.InputStreamReader
import kotlin.concurrent.thread


class ADBHelper private constructor() {
    val TAG = "ADBHelper"

    private val mainHandler by lazy {
        Handler(Looper.getMainLooper())
    }

    init {
        getSU()
    }

    companion object {
        val instance by lazy {
            ADBHelper()
        }
    }

    private fun getSU() {
        ExLog.e(TAG, "su")
        execShell("su", { s ->
            ExLog.e(TAG, "su$s")
        }, { e ->
            e.printStackTrace()
        })
    }

    fun netStatCheck(
        successCallBack: (string: String) -> Unit,
        error: (e: Throwable) -> Unit
    ) {
        execShell("netstat -ntlp", successCallBack, error)
    }

    fun powerDown(successCallBack: () -> Unit, error: (e: Throwable) -> Unit) {
        bootController("reboot -p", successCallBack, error)
    }

    fun reboot(successCallBack: () -> Unit, error: (e: Throwable) -> Unit) {
        bootController("reboot", successCallBack, error)
    }

    private fun bootController(
        cmd: String,
        successCallBack: () -> Unit,
        error: (e: Throwable) -> Unit
    ) {
        execShell(cmd, { s ->
            successCallBack.invoke()
        }, error)
    }


    fun execShell(
        shellCommend: String,
        successCallBack: (string: String) -> Unit,
        error: (e: Throwable) -> Unit
    ) {
        val runtime = Runtime.getRuntime()
        kotlin.runCatching {
            Thread {
                var process = runtime.exec(shellCommend)
                val mReader = BufferedReader(InputStreamReader(process.inputStream))
                val sb = StringBuffer()
                val buffer = CharArray(1024)
                var ch = 0
                ch = mReader.read(buffer)
                while (ch != -1) {
                    sb.append(buffer, 0, ch)
                    ch = mReader.read(buffer)
                }
                mReader.close()
                process.destroy()
                process = null
                mainHandler.post {
                    successCallBack.invoke(sb.toString())
                }
            }.start()

        }.getOrElse {
            error.invoke(it)
        }
    }
}